import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getVisibleProducts } from '../../redux/reducers/productReducer';
import ProductListItem from './ProductListItem';
import { addToCart } from '../../redux/actions/productAction';


class ProductList extends Component {
  render() {
    // 从props上获取需要的数据
    // 注意下面的mapDispatchToProps属性，例如 addToCart
    // addToCart,addToCart,所以需要从 props上获取
    // 如果直接使用，会导致方法没有连接到redux,不会有任何反应
    const { products, addToCart } = this.props;
    return (
      <div>
        {products.map(product => 
          <ProductListItem key={product.id} product={product} onAddToCartHandle={() => addToCart(product.id)}/>
        )}
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    products: getVisibleProducts(state.products)
  }
}

export default connect(
  mapStateToProps,
  { addToCart }
)(ProductList)
